package pers.karl.design.structure.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * 棋子工厂
 */
public class ChessmanFactory {

    /**
     * 存放已创建的棋子对象
     */
    private Map<String, Chessman> chessmanMap;

    private static class Holder {
        private static ChessmanFactory chessmanFactory = new ChessmanFactory();
    }

    private ChessmanFactory() {
        chessmanMap = new HashMap<>();
    }

    public static ChessmanFactory getInstance() {
        return Holder.chessmanFactory;
    }

    /**
     * 获取棋子对象，根据内部状态的相关数据
     * @param shape
     * @param color
     * @param size
     * @return
     */
    public Chessman getChessman(String shape, String color, int size) {
        String key = String.join("-", shape, color, String.valueOf(size));

        Chessman chessman = chessmanMap.get(key);
        if(chessman == null) {
            synchronized (key) {
                if(chessman == null) {

                    chessman = new Chessman(shape, color, size);
                    chessmanMap.put(key, chessman);
                }
            }
        }

        return chessman;
    }


}
